﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Data.SqlClient;

using Shove.Alipay;

public partial class FinanceCenter_AdminDistillMoney : PageBase
{
    protected string gateway = "";
    protected string service = "";
    protected string partner = "";
    protected string sign_type = "";
    protected string _input_charset = "";                                                     //编码类型
    protected string digest_bptb_pay_file = "";                                               //文件摘要
    protected string file_digest_type = "";                                                   //文件摘要算法
    protected string biz_type = "";                                                           //业务类型
    protected string key = "";
    protected string agentID = "";                                                            //代理商ID
    protected string sign = "";                                                               //签名
    protected string bptb_pay_file = "";                                                      //上传的文件地址
    protected string Url = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            tbTime.Text = System.DateTime.Now.ToString("yyyy-MM-dd");

            BindData();

            BindData1();

            BindData2();
        }
    }

    #region Web 窗体设计器生成的代码

    override protected void OnInit(EventArgs e)
    {
        isRequestLogin = true;
        isAtFramePageLogin = true;
        RequestLoginPage = this.Request.Url.AbsoluteUri;        //获取决对Url
        RequestCompetences = Competences.BuildCompetencesList(Competences.DistillMoney);

        base.OnInit(e);
    }

    #endregion

    private void BindData()
    {
        DataTable dt =new DAL.Views.V_Customer().Open("", "Earning3 - EarningBalance3 > 0", "isSurrogate desc, [id]");

        if (dt == null)
        {
            Shove._Web.JavaScript.Alert(this.Page, "数据库连接失败");

            return;
        }

        g.DataSource = dt;
        g.DataBind();
        gPager.Visible = (dt.Rows.Count > 0);
        btnGOAll.Enabled = (dt.Rows.Count > 0);
        btnGOAllOnlinPay.Enabled = (dt.Rows.Count > 0);
    }

    protected void g_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.EditItem)
        {
            double Money = Shove._Convert.StrToDouble(e.Item.Cells[5].Text, 0);
            e.Item.Cells[5].Text = Money.ToString("N");

            double Earning3 = Shove._Convert.StrToDouble(e.Item.Cells[9].Text, 0);
            double EarningBalance3 = Shove._Convert.StrToDouble(e.Item.Cells[10].Text, 0);
            e.Item.Cells[5].Text = (Earning3 - EarningBalance3).ToString("N");
            ((TextBox)e.Item.Cells[6].FindControl("tbMoney")).Text = (Earning3 - EarningBalance3).ToString();

            bool isSurrogate = Shove._Convert.StrToBool(e.Item.Cells[8].Text, false);
            if (isSurrogate)
            {
                e.Item.BackColor = System.Drawing.Color.LightCyan;
                e.Item.ToolTip = "代理商";
            }
        }
    }

    protected void g_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
    {
        long CustomerID = Shove._Convert.StrToLong(e.Item.Cells[7].Text, -1);

        string Return = "";
        int Result = 0;

        if (e.CommandName == "btnGO")
        {
            if (CustomerID < 0)
            {
                PublicFunction.GoError(ErrorNumber.Unknow, "数据参数错误", this.GetType().BaseType.FullName);

                return;
            }

            double EarningNoBalanced = Shove._Convert.StrToDouble(e.Item.Cells[5].Text.Replace(",", ""), 0);
            double Money = Shove._Convert.StrToDouble(((TextBox)e.Item.Cells[6].FindControl("tbMoney")).Text, 0);
            if ((Money < 0) || (Money > EarningNoBalanced))
            {
                Shove._Web.JavaScript.Alert(this.Page, "请输入有效的金额(不大于未结算奖金)。");
                return;
            }

            Customer Customer = new Customer(_Site.ID);
            Customer.ID = CustomerID;
            Return = "";
            Result = Customer.GetCustomerInformationByID(ref Return);
            if (Result < 0)
            {
                PublicFunction.GoError(ErrorNumber.DataReadWrite, "数据读写错误", this.GetType().BaseType.FullName);

                return;
            }

            if (Customer.Balance < Money)
            {
                Shove._Web.JavaScript.Alert(this, "用户帐户余额不足(帐户余额：" + Customer.Balance.ToString() + " 元)。");

                return;
            }

            Result = 0;
            Return = "";

            if (DAL.Procedures.P_CustomerDistill(_Site.ID, Customer.ID, Money, Customer.BankNameDetail, Customer.BankCardNumber, "奖金结算(线下)", 0, _Customer.ID, 1, -1, 2, ref Result, ref Return) < 0)
            {
                Shove._Web.JavaScript.Alert(this.Page, "结算失败");

                return;
            }

            if (Result < 0)
            {
                Shove._Web.JavaScript.Alert(this.Page, Return);

                return;
            }

            if (Customer.ID == _Customer.ID)
            {
                _Customer.GetCustomerInformationByID(ref Return);
            }

            try
            {
                BindData();
            }
            catch
            {
                if (gPager.PageIndex > 0)
                {
                    gPager.PageIndex -= 1;
                    BindData();
                }
            }

            Shove._Web.JavaScript.Alert(this, "此消费ID提款结算成功。", "AdminDistillMoney.aspx");

            return;
        }

        if (e.CommandName == "btnGOOnlinPay")
        {
            if (CustomerID < 0)
            {
                PublicFunction.GoError(ErrorNumber.Unknow, "数据参数错误", this.GetType().BaseType.FullName);

                return;
            }

            double EarningNoBalanced = Shove._Convert.StrToDouble(e.Item.Cells[5].Text.Replace(",", ""), 0);
            double Money = Shove._Convert.StrToDouble(((TextBox)e.Item.Cells[6].FindControl("tbMoney")).Text, 0);
            if ((Money < 0) || (Money > EarningNoBalanced))
            {
                Shove._Web.JavaScript.Alert(this.Page, "请输入有效的金额(不大于未结算奖金)。");

                return;
            }

            Customer Customer = new Customer(_Site.ID);
            Customer.ID = CustomerID;
            Return = "";
            Result = Customer.GetCustomerInformationByID(ref Return);
            if (Result < 0)
            {
                PublicFunction.GoError(ErrorNumber.DataReadWrite, "数据读写错误", this.GetType().BaseType.FullName);

                return;
            }

            //if (Customer.Balance < Money)
            //{
            //    Shove._Web.JavaScript.Alert(this, "用户帐户余额不足(帐户余额：" + Customer.Balance.ToString() + " 元)。");

            //    return;
            //}

            Result = 0;
            Return = "";

            if (DAL.Procedures.P_CustomerDistill(_Site.ID, Customer.ID, Money, Customer.BankNameDetail, Customer.BankCardNumber, "奖金结算(线上)", 0, _Customer.ID, 0, -1, 2, ref Result, ref Return) < 0)
            {
                Shove._Web.JavaScript.Alert(this.Page, "结算失败");

                return;
            }

            if (Result < 0)
            {
                Shove._Web.JavaScript.Alert(this.Page, Return);

                return;
            }

            if (Customer.ID == _Customer.ID)
            {
                _Customer.GetCustomerInformationByID(ref Return);
            }

            try
            {
                BindData();
            }
            catch
            {
                if (gPager.PageIndex > 0)
                {
                    gPager.PageIndex -= 1;
                    BindData();
                }
            }

            Shove._Web.JavaScript.Alert(this, "此消费ID提款结算成功。", "AdminDistillMoney.aspx");

            return;

        }
    }

    protected void gPager_PageWillChange(object Sender, Shove.Web.UI.PageChangeEventArgs e)
    {
        BindData();
    }

    protected void gPager_SortBefore(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
    {
        BindData();
    }

    protected void btnGOAll_Click(object sender, System.EventArgs e)
    {
        int Result = 0;
        string Return = "";

        if (DAL.Procedures.P_CustomerDistillAll(_Customer.ID, 1, -1, 2, ref Result, ref Return) < 0)
        {
            Shove._Web.JavaScript.Alert(this.Page, "结算失败");

            return;
        }

        if (Result < 0)
        {
            Shove._Web.JavaScript.Alert(this.Page, Return);

            return;
        }


        Return = "";
        _Customer.GetCustomerInformationByID(ref Return);

        gPager.PageIndex = 0;
        BindData();

        Shove._Web.JavaScript.Alert(this, "结算成功。", "AdminDistillMoney.aspx");
         
    }

    protected void btnGOAllOnlinPay_Click(object sender, System.EventArgs e)
    {
        int Result = 0;
        string Return = "";

        if (DAL.Procedures.P_CustomerDistillAll(_Customer.ID, 0, -1, 2, ref Result, ref Return) < 0)
        {
            Shove._Web.JavaScript.Alert(this.Page, "结算失败");

            return;
        }

        if (Result < 0)
        {
            Shove._Web.JavaScript.Alert(this.Page, Return);

            return;
        }

        Return = "";
        _Customer.GetCustomerInformationByID(ref Return);

        gPager.PageIndex = 0;
        BindData();

        Shove._Web.JavaScript.Alert(this, "结算成功。", "AdminDistillMoney.aspx");
 
    }


    private void BindData1()
    {
        DataTable dt = new DAL.Views.V_CustomerDistill().Open("", "PaymentType = 0 and [Type] = 2 and Result = 0", "isSurrogate desc");

        if (dt == null)
        {
            Shove._Web.JavaScript.Alert(this.Page, "数据库连接失败");

            return;
        }

        g1.DataSource = dt;
        g1.DataBind();

        gPager1.Visible = (dt.Rows.Count > 0);
        btnAlipayAdd.Enabled = (dt.Rows.Count > 0);
        btnAlipayToAlipayAdd.Enabled = (dt.Rows.Count > 0);
    }

    protected void g1_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.EditItem)
        {
            e.Item.Cells[2].Text += "(" + e.Item.Cells[9].Text + ")";

            double Money = Shove._Convert.StrToDouble(e.Item.Cells[3].Text, 0);
            e.Item.Cells[3].Text = "￥" + Money.ToString("N");

            int Type = Shove._Convert.StrToInt(e.Item.Cells[15].Text, 0);
            e.Item.Cells[5].Text = "月薪";

            int Result = Shove._Convert.StrToInt(e.Item.Cells[21].Text, 0);
            if (Result == 0)
            {
                e.Item.Cells[6].Text = "处理中";
            }
            else if (Result == 2)
            {
                e.Item.Cells[6].Text = "完成";
            }

            e.Item.Cells[20].Text = "2";    //对公对私标志 1 表示对公账号 2 表示对私账号
        }
    }

    protected void g1_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        if (e.CommandName == "btnToBank")
        {
            int CheckedCount = 0;
            double SumMoney = 0;
            string Body = "";

            double Money = 0;

            string CustomerDistillIDs = "";

            Money = Shove._Convert.StrToDouble(e.Item.Cells[17].Text, 0);

            //日期,总金额,总笔数,支付宝帐号(Email)
            //20080418,10,1,53669955@qq.com
            //商户流水号,收款银行户名,收款银行帐号,收款开户银行,收款银行所在省份,收款银行所在市,收款支行名称,金额,对公对私标志,备注
            //2007052801,韦吴石,6221885511000609058,工商银行,广东省,深圳市,工商银行深圳宝安分行,10,2,2132

            Body += e.Item.Cells[1].Text.Trim() + "," + e.Item.Cells[9].Text.Trim() + "," + e.Item.Cells[16].Text.Trim() + "," + e.Item.Cells[14].Text.Trim() + "," + e.Item.Cells[10].Text.Trim() + "," + e.Item.Cells[11].Text.Trim() + "," + e.Item.Cells[15].Text.Trim() + "," + Money.ToString() + "," + (Shove._Convert.StrToBool(e.Item.Cells[20].Text.Trim(), true) ? "2" : "1") + "," + "备注" + "\r\n";

            if (CustomerDistillIDs == "")
            {
                CustomerDistillIDs = e.Item.Cells[1].Text.Trim();
            }
            else
            {
                CustomerDistillIDs += "," + e.Item.Cells[1].Text.Trim();
            }

            SumMoney = Money;
            CheckedCount = 1;

            if ((Body != "") && (CheckedCount > 0) && (SumMoney > 0))
            {
                OnlinePaymentAlipayToBank(CheckedCount, SumMoney, Body, CustomerDistillIDs);
            }

            BindData1();
        }

        if (e.CommandName == "btnToAlipay")
        {
            int Count = 0;
            double SumMoney = 0;
            string Body = "";

            string UserDistillIDs = "";

            //*******************************************************
            SumMoney = Shove._Convert.StrToDouble(e.Item.Cells[3].Text, 0);                      //总金额					0.01～50000.00
            Count = 1;     //批次号即该次付款总笔数
            //*********************************************************

            //注意格式多条用"|" 隔开 //"0039411^92781@qq.com^周长军^0.01^test|0039491^550833185@qq.com^谢凯^0.01^263"
            Body = e.Item.Cells[1].Text + "^" + e.Item.Cells[13].Text + "^" + e.Item.Cells[9].Text + "^" + e.Item.Cells[17].Text + "^日薪"; 


            UserDistillIDs = e.Item.Cells[1].Text;
            OnlinePaymentAlipayToAlipay(Count, SumMoney, Body, UserDistillIDs);

            return;
        }
    }

    protected void btnAlipayAdd_Click(object sender, EventArgs e)
    {
        int CheckedCount = 0;
        double SumMoney = 0;
        string Body = "";

        int i = 0;
        double Money = 0;

        string UserDistillIDs = "";

        for (i = 0; i < g1.Items.Count; i++)
        {
            CheckBox chkBox = (CheckBox)g1.Items[i].Cells[0].FindControl("cbAddAlipay");

            if (chkBox != null && chkBox.Checked)
            {
                Money = Shove._Convert.StrToDouble(g1.Items[i].Cells[17].Text, 0);

                Body += g1.Items[i].Cells[1].Text.Trim() + "," + g1.Items[i].Cells[9].Text.Trim() + "," + g1.Items[i].Cells[16].Text.Trim() + "," + g1.Items[i].Cells[14].Text.Trim() + "," + g1.Items[i].Cells[10].Text.Trim() + "," + g1.Items[i].Cells[11].Text.Trim() + "," + g1.Items[i].Cells[15].Text.Trim() + "," + Money.ToString() + "," + (Shove._Convert.StrToBool(g1.Items[i].Cells[20].Text.Trim(), true) ? "2" : "1") + "," + "备注" + "\r\n";

                if (UserDistillIDs == "")
                {
                    UserDistillIDs = g1.Items[i].Cells[1].Text.Trim();
                }
                else
                {
                    UserDistillIDs += "," + g1.Items[i].Cells[1].Text.Trim();
                }

                SumMoney += Money;
                CheckedCount++;
            }
        }

        if ((Body != "") && (CheckedCount > 0) && (SumMoney > 0))
        {
            OnlinePaymentAlipayToBank(CheckedCount, SumMoney, Body, UserDistillIDs);
        }
        else
        {
            Shove._Web.JavaScript.Alert(this, "您没有选中任何选项。");

            return;
        }
    }

    protected void btnAlipayToAlipayAdd_Click(object sender, EventArgs e)
    {
        int CheckedCount = 0;
        double SumMoney = 0;
        string Body = "";

        int i = 0;
        double Money = 0;

        string UserDistillIDs = "";

        for (i = 0; i < g1.Items.Count; i++)
        {
            CheckBox chkBox = (CheckBox)g1.Items[i].Cells[0].FindControl("cbAddAlipay");

            if (chkBox != null && chkBox.Checked)
            {
                Money = Shove._Convert.StrToDouble(g1.Items[i].Cells[17].Text, 0);

                if (Body != "")
                {
                    Body += "|" + g1.Items[i].Cells[1].Text + "^" + g1.Items[i].Cells[13].Text + "^" + g1.Items[i].Cells[9].Text + "^" + g1.Items[i].Cells[17].Text + "^日薪";
                }
                else
                {
                    Body += g1.Items[i].Cells[1].Text + "^" + g1.Items[i].Cells[13].Text + "^" + g1.Items[i].Cells[9].Text + "^" + g1.Items[i].Cells[17].Text + "^日薪";
                }

                if (UserDistillIDs == "")
                {
                    UserDistillIDs = g1.Items[i].Cells[1].Text.Trim();
                }
                else
                {
                    UserDistillIDs += "," + g1.Items[i].Cells[1].Text.Trim();
                }

                SumMoney += Money;
                CheckedCount++;
            }
        }

        if ((Body != "") && (CheckedCount > 0) && (SumMoney > 0))
        {
            OnlinePaymentAlipayToAlipay(CheckedCount, SumMoney, Body, UserDistillIDs);
        }
        else
        {
            Shove._Web.JavaScript.Alert(this, "您没有选中任何选项。");

            return;
        }
    }

    protected void gPager1_PageWillChange(object Sender, Shove.Web.UI.PageChangeEventArgs e)
    {
        BindData1();
    }

    private void BindData2()
    {
        DateTime dtime = Shove._Convert.StrToDateTime(tbTime.Text,DateTime.Now.ToString());

        //DataTable dt = DAL.Views.V_CustomersDistill.Select("", "(PaymentType = -30 or PaymentType = -20 or PaymentType = 1 or PaymentType = 2 or PaymentType = 3) and [Type] = 1 and (Result = 1 or Result = 2)", "isSurrogate desc");
        DataTable dt = new DAL.Views.V_CustomerDistill().Open("", "[Type] = 2 and year([Datetime]) = " + dtime.Year + " and Month([Datetime]) = " + dtime.Month + " and Day([Datetime]) = " + dtime.Day + " and PaymentType <> 0 and Result = 2", "isSurrogate desc");

        if (dt == null)
        {
            Shove._Web.JavaScript.Alert(this.Page, "数据库连接失败");

            return;
        }

        g2.DataSource = dt;
        g2.DataBind();

        gPager2.Visible = (dt.Rows.Count > 0);
    }

    protected void g2_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.EditItem)
        {
            int PaymentType = Shove._Convert.StrToInt(e.Item.Cells[18].Text, 0);
            int Result = Shove._Convert.StrToInt(e.Item.Cells[21].Text, 0);

            e.Item.Cells[2].Text += "(" + e.Item.Cells[9].Text + ")";

            double Money = Shove._Convert.StrToDouble(e.Item.Cells[3].Text, 0);
            e.Item.Cells[3].Text = "￥" + Money.ToString("N");

            if (PaymentType == 1)
            {
                e.Item.Cells[5].Text = "月薪" + " (线下转账)";
            }
            else if (PaymentType == 2)
            {
                e.Item.Cells[5].Text = "月薪" + " (在线转账到银行卡)";
            }
            else if (PaymentType == 3)
            {
                e.Item.Cells[5].Text = "月薪" + " (在线转账到支付宝)";
            }

            e.Item.Cells[17].Text = "月薪";

            e.Item.Cells[18].Text = "2";    //对公对私标志 1 表示对公账号 2 表示对私账号

            Button btnOK = (Button)e.Item.Cells[7].FindControl("btnOK");

            if (Result == 1)
            {
                e.Item.Cells[6].Text = "处理中";
            }
            else if (Result == 2)
            {
                e.Item.Cells[6].Text = "完成";
            }

            if (PaymentType != 1)
            {
                if ((Result == 2) && (PaymentType < 0))
                {
                    btnOK.Enabled = true;
                }
                else
                {
                    btnOK.Enabled = false;
                }
            }
            else
            {
                btnOK.Enabled = false;
            }
        }

        e.Item.Cells[0].Visible = false;
    }

    protected void gPager2_PageWillChange(object Sender, Shove.Web.UI.PageChangeEventArgs e)
    {
        BindData2();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        BindData2();
    }

    protected void btnDownload_Click(object sender, EventArgs e)
    {
        BindData2();
    }

    protected void g2_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        int Result = 0;
        string Return = "";

        if (e.CommandName == "btnOK")
        {
            if (DAL.Procedures.P_CustomerDistillUpdate(Shove._Convert.StrToLong(e.Item.Cells[1].Text, 0), Shove._Convert.StrToLong(e.Item.Cells[14].Text, 0), Shove._Convert.StrToDouble(e.Item.Cells[20].Text, 0), _Customer.ID, ref Result, ref Return) < 0)
            {
                Shove._Web.JavaScript.Alert(this.Page, "数据处理失败");

                return;
            }

            if (Result < 0)
            {
                Shove._Web.JavaScript.Alert(this.Page, Return);

                return;
            }

            BindData2();

            Shove._Web.JavaScript.Alert(this.Page, "处理成功");

            return;
        }
    }

    protected void btnPanel1_Click(object sender, EventArgs e)
    {
        BindData();

        btnPanel1.Style.Add("background-color", "#E1EFFA");
        Panel1.Visible = true;
        tdPanel1.Style.Add("background-color", "#E1EFFA");

        btnPanel2.Style.Add("background-color", "#F0F0F0");
        Panel2.Visible = false;
        tdPanel2.Style.Add("background-color", "#F0F0F0");

        btnPanel3.Style.Add("background-color", "#F0F0F0");
        Panel3.Visible = false;
        tdPanel3.Style.Add("background-color", "#F0F0F0");
    }

    protected void btnPanel2_Click(object sender, EventArgs e)
    {
        BindData1();

        btnPanel1.Style.Add("background-color", "#F0F0F0");
        Panel1.Visible = false;
        tdPanel1.Style.Add("background-color", "#F0F0F0");

        btnPanel2.Style.Add("background-color", "#E1EFFA");
        Panel2.Visible = true;
        tdPanel2.Style.Add("background-color", "#E1EFFA");

        btnPanel3.Style.Add("background-color", "#F0F0F0");
        Panel3.Visible = false;
        tdPanel3.Style.Add("background-color", "#F0F0F0");
    }

    protected void btnPanel3_Click(object sender, EventArgs e)
    {
        BindData2();

        btnPanel1.Style.Add("background-color", "#F0F0F0");
        Panel1.Visible = false;
        tdPanel1.Style.Add("background-color", "#F0F0F0");

        btnPanel2.Style.Add("background-color", "#F0F0F0");
        Panel2.Visible = false;
        tdPanel2.Style.Add("background-color", "#F0F0F0");

        btnPanel3.Style.Add("background-color", "#E1EFFA");
        Panel3.Visible = true;
        tdPanel3.Style.Add("background-color", "#E1EFFA");
    }

    protected void OnlinePaymentAlipayToBank(int Count, double SumMoney, string Body, string UserDistillIDs)
    { 
        //业务参数赋值；
        partner = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_CustomerNumber", "");		//partner		合作伙伴ID			保留字段
        key = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_MD5Key", "");   //partner账户的支付宝安全校验码

        gateway = "https://www.alipay.com/cooperate/gateway.do";
        service = "bptb_pay_file";
        sign_type = "MD5";
        _input_charset = "GB2312";                                                  //编码类型
        file_digest_type = "MD5";                                                   //文件摘要算法
        biz_type = "d_sale";                                                        //业务类型

        agentID = "2088001456282873";

        Shove.Alipay.Alipay ap = new Shove.Alipay.Alipay();
        DateTime dtNow = DateTime.Now;

        string FileName = "";
        string FileAddr = "";
        string ZipFileName = "";
        string ZipFileAddr = "";

        int i = 0;

        if ((Body != "") && (Count > 0) && (SumMoney > 0))
        {
            string strDateTime = dtNow.ToString("yyyyMMdd");

            #region     CSV文件标准格式

            //日期,总金额,总笔数,支付宝帐号(Email)
            //20080418,10,1,53669955@qq.com
            //商户流水号,收款银行户名,收款银行帐号,收款开户银行,收款银行所在省份,收款银行所在市,收款支行名称,金额,对公对私标志,备注
            //2007052801,韦吴石,6221885511000609058,工商银行,广东省,深圳市,工商银行深圳宝安分行,10,2,2132

            #endregion

            #region 给Body加表头

            Body = "日期,总金额,总笔数,支付宝帐号(Email)\r\n" + strDateTime + "," + SumMoney.ToString() + "," + Count.ToString() + "," + PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_CustomerName", "") + "\r\n" + "商户流水号,收款银行户名,收款银行帐号,收款开户银行,收款银行所在省份,收款银行所在市,收款支行名称,金额,对公对私标志,备注\r\n" + Body;
            
            #endregion

            #region 1、根据规则构建文件名;2、在根目录 AlipayPayment/PABX/ 下创建.cvs 文件 并且写入Body内容 3、压缩cvs文件 --> .zip 压缩包

            System.Random rad = new Random();
            string Num = rad.Next(1, 999).ToString();
            Num = Num + dtNow.Hour.ToString() + dtNow.Minute.ToString() + dtNow.Second.ToString();
            Num = Num.PadLeft(9, '0');

            FileName = "PAPX_" + strDateTime + "_P" + Num + ".csv".ToLower();
            FileAddr = MapPath("../AlipayPayment/PABX/" + FileName).ToLower();
            ZipFileName = "PAPX_" + strDateTime + "_P" + Num + ".Zip".ToLower();
            ZipFileAddr = MapPath("../AlipayPayment/PABX/" + ZipFileName).ToLower();

            if (!System.IO.File.Exists(FileAddr))
            {
                try
                {
                    Shove._IO.File.WriteFile(FileAddr, Body);
                }
                catch
                {
                    Shove._Web.JavaScript.Alert(this.Page, "CSV文件写入异常");

                    return;
                }
            }
            else
            {
                Shove._Web.JavaScript.Alert(this.Page, "文件写已存在");

                return;
            }

            if (System.IO.File.Exists(FileAddr))
            {
                if (!System.IO.File.Exists(ZipFileAddr))
                {
                    try
                    {
                        Shove._IO.File.Compress(FileAddr, ZipFileAddr);
                    }
                    catch
                    {
                        Shove._Web.JavaScript.Alert(this.Page, "文件压缩出现异常");

                        return;
                    }
                }

            }
            else
            {
                Shove._Web.JavaScript.Alert(this.Page, "CSV文件不存在");

                return;
            }
        }

        if (!System.IO.File.Exists(ZipFileAddr))
        {
            Shove._Web.JavaScript.Alert(this.Page, "ZIP文件不存在");

            return;
        }

        #endregion

          
            // 读取压缩文件至二进制数组
            byte[] Date = System.IO.File.ReadAllBytes(ZipFileAddr);

            // digest_bptb_pay_file：文件摘要 _input_charset：编码类型
            digest_bptb_pay_file = Shove.Alipay.Alipay.GetMD5(Date, _input_charset);

            // 上传文件按参数构建
            string[] Sortedstr = ap.GetUploadParams
                (
                service,
                _input_charset,                 //编码类型
                partner,                        //partner	合作伙伴ID	保留字段
                file_digest_type,               //文件摘要算法
                biz_type,                       //业务类型
                agentID
                );                              //签名

            // 读取压缩文件至文件流
            FileStream fs = new FileStream(ZipFileAddr, FileMode.Open, FileAccess.Read, FileShare.Read);
            string ContentType = "application/octet-stream";
            // 文件流写人二进制数组
            byte[] fileBytes = new byte[fs.Length];
            fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            // 生成需要上传的二进制数组
            CreateBytes cb = new CreateBytes();
            // 所有表单数据
            ArrayList bytesArray = new ArrayList();
            // 普通表单数据
            string[] fields = new string[Sortedstr.Length + 1];

            // 拆分参数数组 加入到所有表单数据和普通表单数据数组
            char[] delimiterChars = { '=' };
            for (i = 0; i < Sortedstr.Length; i++)
            {
                string fieldName = Sortedstr[i].Split(delimiterChars)[0];
                string fieldValue = Sortedstr[i].Split(delimiterChars)[1];

                bytesArray.Add(cb.CreateFieldData(fieldName, fieldValue));
                fields[i] = fieldName + "=" + fieldValue;
            }

            // 根据Key,普通表单数据(fields) 返回签名(sign)
            sign = AlipayCommon.GetSign(fields, key).Trim();
           
            // 普通数据表单加入文件摘要
            fields[i] = "digest_bptb_pay_file=" + digest_bptb_pay_file;

            // cb需要上传的二进制数组
            // 所有表单数据加入文件摘要 签名 签名算法 
            bytesArray.Add(cb.CreateFieldData("digest_bptb_pay_file", digest_bptb_pay_file));
            bytesArray.Add(cb.CreateFieldData("sign", sign));
            bytesArray.Add(cb.CreateFieldData("sign_type", "MD5"));

            // 所有表单数据加入读取压缩上传文件的文件流二进制数组(fileBytes)
            bytesArray.Add(cb.CreateFieldData("bptb_pay_file", ZipFileAddr, ContentType, fileBytes));

            // 合成所有表单并生成二进制数组为待上传的二进制数组
            byte[] bytes = cb.JoinBytes(bytesArray);

            //byte[] responseBytes = Shove._String.Compress("上传成功");
            //bool uploaded = true;

            // 返回的内容
            byte[] responseBytes;
            // 上传到指定Url  获取返回结果      
            bool uploaded = cb.UploadData(gateway, bytes, out responseBytes);
            string UploadResult = System.Text.Encoding.Default.GetString(responseBytes);

            if (UploadResult.IndexOf("上传成功") >= 0)
            //if (UploadResult.IndexOf("x阢騍?H?\0\a?+") >= 0)
            {
                //写入数据库（FileName）

                if (DAL.Procedures.P_CustomerDistillsUpdate(ZipFileName, UserDistillIDs, 2, 300) < 0)
                {
                    PublicFunction.WriteLogini("P_CustomerDistillsUpdate 过程执行失败 文件名为：" + ZipFileName);
                }

                Shove._Web.JavaScript.Alert(this.Page, UploadResult + "请耐心等待处理结果！");

                BindData1();
            }
            else
            {
                try
                {
                    File.Delete(FileAddr);
                    File.Delete(ZipFileAddr);
                }
                catch
                {
                }

                Shove._Web.JavaScript.Alert(this.Page, UploadResult);

                return;
            }
    }

    protected void OnlinePaymentAlipayToAlipay(int Count, double SumMoney, string Body, string UserDistillIDs)
    {
        //业务参数赋值；
        partner = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_UserNumber", "");		//partner		合作伙伴ID			保留字段
        key = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_MD5Key", "");   //partner账户的支付宝安全校验码
        //**************e******************************************
        string email = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_UserName", "");             //付款人账号
        string account_name = PublicFunction.GetOptionsAsString("OnlinePayOut_Alipay_RealityName", "");		//			账户真实姓名 

        string gateway = "https://www.alipay.com/cooperate/gateway.do?";	//'支付接口
        string _input_charset = "utf-8";
        string service = "batch_trans_notify";
        string sign_type = "MD5";

        DateTime dtNow = DateTime.Now;
        string pay_date = dtNow.ToString("yyyyMMdd");   // 付款日期   //注意格式

        //*******************************************************
        System.Random rad = new Random();
        string Num = rad.Next(1, 99).ToString();
        Num = Num.PadLeft(2, '0');
        string batch_no = dtNow.ToString("yyyyMMddhhmmss") + Num;	//		批量付款订单号 日期(20070412)+16位序列号
        string batch_fee = SumMoney.ToString();                      //总金额					0.01～50000.00
        string batch_num = Count.ToString();     //批次号即该次付款总笔数
        //*********************************************************
        string detail_data = Body; //注意格式多条用"|" 隔开 //"0039411^92781@qq.com^周长军^0.01^test|0039491^550833185@qq.com^谢凯^0.01^263"
        string notify_url = Shove._Web.Utility.GetUrl() + "/OnlinePayment/Alipay/AlipayNotify.aspx"; //服务器通知返回接口

        //Shove.Database.MSSQL.ExecuteNonQuery("update T_CustomerDistills set PaymentType = 3, Result = 1 where [id] in (" + UserDistillIDs + ")");
        if (DAL.Procedures.P_CustomerDistillsUpdate("", UserDistillIDs, 3, 300) < 0)
        {
            PublicFunction.WriteLogini("P_CustomerDistillsUpdate 过程执行失败");
        }

        Shove.Alipay.Alipay ap = new Shove.Alipay.Alipay();
        string aliay_url = ap.CreatUrl(
             gateway,
             service,
             partner,
             sign_type,
             batch_no,
             account_name,
             batch_fee,
             batch_num,
             email,
             pay_date,
             detail_data,
             key,
             notify_url,
             _input_charset
            );

        Response.Redirect(aliay_url, true);                                        //可以采用表单（post）传递数据
        //this.Response.Write("<script language='javascript'>window.top.location.href='" + aliay_url + "'</script>");

        return;
    }
}
